<template>
  <div class="app-container" >
    <div class="filter-container">
      <el-select filterable v-model="searchKey.shopId" clearable class="filter-item" :placeholder="$t('请选择门店')">
        <el-option v-for="item in shops" :value="item.id" :label="item.name"></el-option>
      </el-select>
      <el-select filterable v-model="searchKey.adminId" clearable class="filter-item" :placeholder="$t('请选择操作员')">
        <el-option v-for="item in admins" :value="item.id" :label="item.username"></el-option>
      </el-select>
      <el-button icon="el-icon-search" @click="handleFilter" type="success">{{$t('搜索')}}</el-button>
      <el-button v-permission="['GET /admin/p/config_posad_upload']" @click="posAdUploader" type="primary">{{$t('上传')}}<i class="el-icon-upload el-icon--right"></i></el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="posadlist" :element-loading-text="$t('Searching')" height="700" fit highlight-current-row>
      <el-table-column type="index" :index="getIndex" width="50"></el-table-column>

      <el-table-column align="center" min-width="100" :label="$t('标题')" prop="imgTitle"/>
      <el-table-column align="center" :label="$t('宣传广告')" prop="imgObj">
        <template slot="header" slot-scope="{row}">
          {{$t('宣传广告')}}
          <i class="el-icon-picture"></i>
        </template>
        <template slot-scope="scope">
          <el-image @click="designatedImg(scope.row.imgObjs)" preview-src-list style="border-radius:7%;width:65px" :src="scope.row.imgObjs[0].url"  width="20" lazy>
            <div slot="error" class="image-slot">
              <i @click="designatedImg(scope.row.imgObjs)" style="font-size: 65px" class="el-icon-picture-outline-round"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" min-width="100" :label="$t('宣传门店')" prop="imgPath">
        <template slot="header" slot-scope="{row}">
          {{$t('宣传门店')}}
          <i class="el-icon-s-shop"></i>
        </template>
        <template slot-scope="scope">
          <el-tag v-if="scope.row.type==0" type="success">{{ $t('所有门店') }}</el-tag>
          <el-tag @click.native="designatedStore(scope.row.shopIds)" type="warning" v-else >{{ $t('指定门店') }} <i class="el-icon-view"></i></el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" min-width="100" :label="$t('操作员')" prop="uploaderName">
        <template slot="header" slot-scope="{row}">
          {{$t('操作员')}}
          <i class="el-icon-user-solid"></i>
        </template>
      </el-table-column>

      <el-table-column align="center" min-width="100" :label="$t('广告开始时间')" prop="startTime">
        <template slot="header" slot-scope="{row}">
          {{$t('广告开始时间')}}
          <i class="el-icon-timer"></i>
        </template>
      </el-table-column>
      <el-table-column align="center" min-width="100" :label="$t('广告结束时间')" prop="endTime">
        <template slot="header" slot-scope="{row}">
          {{$t('广告结束时间')}}
          <i class="el-icon-timer"></i>
        </template>
      </el-table-column>
      <el-table-column align="center" min-width="140" :label="$t('状态')" prop="enabled">
        <template slot="header" slot-scope="{row}">
          {{$t('状态')}}
          <el-popover placement="top-start" title="" trigger="click" :content="$t('过期不会生效')">
            <i class="el-icon-warning" style="color: #f8c564" slot="reference"></i>
          </el-popover>

        </template>
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isOpen"
            @change="isEnabled(scope.row)"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1" :nactive-value="0"
            :active-text="$t('开启')"
            :inactive-text="$t('关闭')">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column align="center" min-width="100" :label="$t('备注')" prop="remark"/>
      <el-table-column align="center" min-width="100" :label="$t('添加时间')" sortable prop="addTime"/>
      <el-table-column align="center" :label="$t('Operate')" class-name="small-padding fixed-width"  width="200">
        <template slot="header" slot-scope="{row}">
          {{$t('Operate')}}
          <i class="el-icon-setting"style="color: #d35e32"></i>
        </template>
        <template slot-scope="scope">
          <el-row>
            <el-badge :value="scope.row.staleDated?'':$t('过期')" :type="scope.row.staleDated?'primary':'warning'" class="item">
              <el-button icon="el-icon-edit"  size="mini" @click="handleEdit(scope.row)" >{{ $t('编辑') }}</el-button>
            </el-badge>
            <el-button icon="el-icon-delete"  size="mini" type="danger"  @click="handleDelete(scope.$index,scope.row)" >{{ $t('删除') }}</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>


    <pagination v-show="totalCount > 0" :total="totalCount" :page.sync="searchKey.page" :limit.sync="searchKey.limit"
                @pagination="getPosAdList" />

    <el-tooltip placement="top" :content="$t('返回顶部')">
      <back-to-top :visibility-height="100" />
    </el-tooltip>

    <el-dialog :title="$t('所有门店')" :visible.sync="shopsTableVisible" show-close="false" center="true" width="30%">
      <el-tag style="margin: 4px 5px auto;" type="warning" v-for="item in shopIdNames" :label="item.name" :value="item.name">{{ item.name }}</el-tag>
    </el-dialog>
    <el-dialog :title="$t('宣传广告')" :visible.sync="imgsTableVisible" show-close="false" center="true" width="30%">
      <img style="margin-left: 5px;width: 100px;height: 100px" type="warning" v-for="item in imgObjs" :label="item.url" :value="item.url" :src="item.url" />
    </el-dialog>
    <!--  上传框-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="posadFormVisible">
      <el-form-item v-model="posadForm.id" :label="$t('备注')" :label-width="formLabelWidth" prop="id">
      </el-form-item>
      <el-form :model="posadForm" :rules="posadFormRules" ref="posadFormRef">
        <el-form-item :label="$t('宣传门店')" :label-width="formLabelWidth" prop="type">
          <el-radio-group v-model="posadForm.type">
            <el-radio-button :label="0" >{{$t('所有门店')}}</el-radio-button>
            <el-radio-button :label="1" >{{$t('指定门店')}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="posadForm.type===1" :label="$t('请选择门店')" :label-width="formLabelWidth" prop="shopIds">
          <el-select v-model="posadForm.shopIds" multiple clearable class="filter-item" :placeholder="$t('请选择门店')">
            <el-option v-for="item in shops" :value="item.id" :label="item.name">{{item.name}}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('标题')" :label-width="formLabelWidth" prop="imgTitle">
          <el-input v-model="posadForm.imgTitle"></el-input>
        </el-form-item>
        <el-form-item :label="$t('宣传广告')" :label-width="formLabelWidth" prop="imgPath">
          <el-upload
            accept=".jpg,.jpeg,.png,.gif"
            :on-success="uploadUrl"
            drag
            class="upload-posad"
            :action="uploadMinioPath"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :limit="5"
            :file-list="imgObjs"
            :on-exceed="handleExceed"
            list-type="picture">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">{{$t('将文件拖到此处，或')}}<em>{{$t('点击上传')}}</em></div>
            <div slot="tip" class="el-upload__tip">{{$t('只能上传jpg/jpeg/png/gif文件，且不超过100MB')}}</div>
          </el-upload>
        </el-form-item>
        <el-form-item :label="$t('宣传时间')" :label-width="formLabelWidth" prop="publicityTime">
          <el-col :span="11">
            <el-date-picker v-model="posadForm.startTime" type="datetime" placeholder="开始时间"
                            value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;" />
          </el-col>
          <el-col :span="2" class="line">～</el-col>
          <el-col :span="11">
            <el-date-picker v-model="posadForm.endTime" type="datetime" placeholder="结束时间"
                            value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;" />
          </el-col>
        </el-form-item>
        <el-form-item :label="$t('备注')" :label-width="formLabelWidth" prop="remark">
          <el-input v-model="posadForm.remark"></el-input>
        </el-form-item>
        <el-form-item :label="$t('状态')" :label-width="formLabelWidth" prop="isOpen">
          <el-switch
            v-model="posadForm.isOpen"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1" :nactive-value="0"
            :active-text="$t('开启')"
            :inactive-text="$t('关闭')">
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-error" @click="posadFormVisible = false">{{$t('取消')}}</el-button>
        <el-button icon="el-icon-refresh" @click="resetForm('posadFormRef')">{{$t('重置数据')}}</el-button>
        <el-button v-if="dialogStatus=='create'" icon="el-icon-position" @click="posAdSubmit" type="success" >{{$t('提交上传')}}</el-button>
        <el-button v-else icon="el-icon-edit" @click="posAdEdit" type="success" >{{$t('提交编辑')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import BackToTop from '@/components/BackToTop'
import { allForPerm } from '@/api/shop'
import { uploadMinioPath } from '@/api/storage'
import { allAdmin } from '@/api/admin'
import { posAdSearchAll , posEnabled ,posAdShopS ,posAdUpload,posAdDeleted,posAdUpdate} from '@/api/posad'
import ElColorAlphaSlider from "element-ui/packages/color-picker/src/components/alpha-slider";
import PrimaryAudio from "@/views/layout/components/PlayAudio"
export default {
  name: "configPosad",
  components: { ElColorAlphaSlider, BackToTop, Pagination ,PrimaryAudio},
  data() {
    return {
      //音效组

      fileList: [],
      textMap: {
        create: this.$t('上传广告'),
        update: this.$t('编辑')
      },
      posAdDeleteIds:[],
      dialogStatus:'',
      shops:[],
      admins:[],
      enabled:1,
      posadlist:[],
      searchKey: {
        page: 1,
        limit: 20,
        adminId:undefined,
        shopId: undefined
      },
      listLoading: true,
      totalCount:0,
      shopsTableVisible: false,
      imgsTableVisible: false,
      posadFormVisible: false,
      shopIdNames:[],
      imgObjs:[],
      posadForm:{
        shopIds:[],
        type:0,
        imgObj:[],
        imgTitle:'',
        remark:'',
        startTime:'',
        endTime:'',
        isOpen:0
      },
      formLabelWidth: '120px',
      uploadMinioPath,
      posadFormRules:{
        shopIds:[
          { required: true, message: this.$t('请选择门店'), trigger: 'blur' }
        ],
        imgObj:[
          { required: true, message: this.$t('请上传宣传画廊'), trigger: 'blur' }
        ],
        imgTitle:[
          { required: true, message: this.$t('请填写标题'), trigger: 'blur' }
        ]/*,
        adTime:[
          { required: true, message: '请指定宣传 开始|结束 时间', trigger: 'blur' }
        ]*/
      }
    }
  },
  created() {
    this.getPosAdList()
    allForPerm().then(response=>{
      this.shops = response.data.data.list
    }),
      allAdmin().then(response=>{
        this.admins = response.data.data
      })
  },
  methods: {
    //获取数据列表
    getPosAdList(){
      this.listLoading = true
      posAdSearchAll(this.searchKey).then(response=>{
        this.posadlist = response.data.data.content
        this.totalCount = response.data.data.totalCount
        this.limit = response.data.data.pageSize
        //this.page = this.page==1?response.data.data.pageNum:1
        this.page = response.data.data.pageNum
        //console.log(response)
        this.listLoading = false
      }).catch(() => {
        this.posadlist = []
        this.totalCount = 0
        this.listLoading = false
      })
    },
    //开启｜关闭
    isEnabled(row){
      const posAdUpdate={
        isOpen:(row.isOpen==true?1:0),
        id:row.id
      }
      console.log(posAdUpdate)
      posEnabled(posAdUpdate).then(res=>{

        const h = this.$createElement
        this.$notify.success({
          dangerouslyUseHTMLString: true,
          message: h('PrimaryAudio', {
            props: {
              msg:  row.isOpen==true?this.$t('已开启'):this.$t('已关闭'),
              type: 'open'
            },
          }),
        })
      }).catch(response => {
        row.isOpen=false
        this.$notify.warning({
          title: this.$t('Failed'),
          message: this.$t(response.data.errmsg)
        })
      })
    },
    //查看指定门店
    designatedStore(shopIds){
      this.shopsTableVisible= true
      posAdShopS(shopIds).then(res=>{
        this.shopIdNames=res.data.data
      })
    },
    //查看所有广告
    designatedImg(imgObjs){
      this.imgsTableVisible= true
      this.imgObjs = imgObjs
    },
    //查询加载列表
    handleFilter() {
      this.listLoading = true
      this.searchKey.page = 1
      this.getPosAdList()
    },
    resetPosAdForm() {
      this.posadForm={
        id: undefined,
        shopIds:[],
        type:0,
        imgObj:[],
        imgTitle:'',
        remark:'',
        startTime:'',
        endTime:'',
        isOpen:0
      }
    },
    //点击上传按钮
    posAdUploader(){
      this.resetPosAdForm()
      this.imgObjs=[]
      this.posadFormVisible = true
      this.dialogStatus='create'
      this.$nextTick(() => {
        this.$refs['posadFormRef'].clearValidate()
      })
    },
    handleRemove(file, fileList) {
      this.imgObjs = fileList
      let index = this.posadForm.imgObj.indexOf(file.id);
      this.posadForm.imgObj.splice(index, 1)
    },
    handlePreview(file) {
      console.log(file);
    },
    //上传广告
    uploadUrl: function (response) {
      this.posadForm.imgObj.push(response.data.id)
      this.fileList.push(response.data.id)

      const h = this.$createElement
      this.$notify.success({
        dangerouslyUseHTMLString: true,
        message: h('PrimaryAudio', {
          props: {
            msg: this.$t('上传完毕'),
            type: 'success'
          },
        }),
      })
    },
    handleExceed(files, imgObj) {
      const h = this.$createElement
      this.$notify.warning({
        title: this.$t('Warning'),
        dangerouslyUseHTMLString: true,
        message: h('PrimaryAudio', {
          props: {
            msg:  this.$t('当前限制选择 5 个文件，本次选择了 1 个文件，共选择了 5 个文件'),
            type: 'warning'
          },
        }),
      })

    },
    getIndex(index) {
      return (index + 1) + (this.searchKey.page - 1) * this.searchKey.limit;
    },
    //提交数据
    posAdSubmit(){
      this.$refs.posadFormRef.validate(valid =>{
        if(!valid) return;
        this.posadForm.isOpen=this.posadForm.isOpen===true?1:0
        posAdUpload(this.posadForm).then(res=>{
          this.$refs['posadFormRef'].resetFields();
          this.posadForm.imgObj=[]
          const h = this.$createElement
          this.$notify.success({
            title: this.$t('Success!'),
            dangerouslyUseHTMLString: true,
            message: h('PrimaryAudio', {
              props: {
                msg:  this.$t('上传成功,您还可以继续上传或离开'),
                type: 'success'
              },
            }),
          })
        }).catch(res => {
          this.$notify.warning({
            title: this.$t('Failed'),
            message: this.$t(res.data.errmsg)
          })
        })
      })
    },
    //提交编辑数据
    posAdEdit(){
      this.$refs.posadFormRef.validate(valid =>{
        if(!valid) return;
        this.posadForm.isOpen=this.posadForm.isOpen?1:0
        posAdUpdate(this.posadForm).then(res=>{
          const h = this.$createElement
          this.$notify.success({
            title: this.$t('Success!'),
            dangerouslyUseHTMLString: true,
            message: h('PrimaryAudio', {
              props: {
                msg: this.$t('编辑成功,您还可以继续编辑或离开'),
                type: 'success'
              },
            }),
          })
          //刷新列表
          this.getPosAdList()
        }).catch(res => {
          this.$notify.warning({
            title: this.$t('Failed'),
            message: this.$t(res.data.errmsg)
          })
        })
      })
    },
    //重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //点击编辑
    handleEdit(row){
      console.log(row)
      this.imgObjs = row.imgObjs
      this.posadFormVisible= true
      this.posadForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.$nextTick(() => {
        this.$refs['posadFormRef'].clearValidate()
      })
    },
    //点击删除
    handleDelete(index,row) {
      this.$confirm(this.$t('Confirm_Delete?'), this.$t('Hint'), {
        confirmButtonText: this.$t('Confirm'),
        cancelButtonText: this.$t('Cancel'),
        type: 'warning'
      }).then(() => {
        this.doDelete(row)
        this.posadlist.splice(index, 1);
      });
    },
    //开始删除
    doDelete(row) {
      this.posAdDeleteIds.push(row.id)
      posAdDeleted(this.posAdDeleteIds)
        .then(res=> {
          const h = this.$createElement
          this.$notify.success({
            title: this.$t('Success!'),
            dangerouslyUseHTMLString: true,
            message: h('PrimaryAudio', {
              props: {
                msg: this.$t('Deleted'),
                type: 'deldeted'
              },
            }),
          })
        })
        .catch(response => {
          this.$notify.error({
            title: this.$t('Failed'),
            message: this.$t('Failed')
          })
        })
    },
  }


}
</script>

<style scoped>
.el-button{
  margin-left: 10px;
}
.app-container{
  margin: auto;
}
img{ width:50px;  height:50px;  border-radius: 15%;  }
img:hover{
  cursor: pointer;
}
.item {
  margin-top: 10px;
  margin-right: 20px;
}
</style>
